<?php
namespace app\common\controller;


class Curl
{
    private static $instance;

    private function __construct(){}

    /**
     * 获得单例
     * @return Curl
     */
    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    /**
     * 发送curl请求
     * @param string $url
     * @param mixed $data
     * @param bool $post
     * @return mixed|string
     */
    public function send($url, $data = null, $post = true)
    {
        # 初始化一个cURL会话
        $curl = curl_init();

        // 设置请求选项, 包括具体的url
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);  // 禁用后cURL将终止从服务端进行验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if ($post == true) {
            curl_setopt($curl, CURLOPT_POST, 1);  // 设置为post请求类型
        }

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  // 设置具体的post数据
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);  // 执行一个cURL会话并且获取相关回复

        curl_close($curl);  // 释放cURL句柄,关闭一个cURL会话

        if ($response === false) {
            return "curl函数错误: ".curl_error($curl);
        }
        return $response;
    }

    /**
     * xml字符转对象
     * @param string $xmlstring
     * @return array
     */
    public function xml2array($xmlstring)
    {
        $obj = simplexml_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOCDATA);
        return json_decode(json_encode($obj, 256), true);
    }

    /**
     * xml字符转json字符
     * @param string $xmlstring
     * @return string
     */
    public function xml2json($xmlstring)
    {
        return json_encode($this->xml2array($xmlstring), 256);
    }
}